<template>
  <div class="ai-chat-page">
    
    <!-- AI对话区域 -->
    <div class="chat-container">
      <div class="chat-header">
        <div class="header-left">
          <h1>AI智能助手</h1>
          <p class="ai-status">随时为您提供帮助</p>
        </div>
        <button class="search-toggle-btn" @click="toggleSearchSidebar" title="搜索历史">
          <span class="search-icon">🔍</span>
        </button>
      </div>
      
      <!-- 侧边搜索内容列表 -->
      <div class="search-sidebar" :class="{ active: showSearchSidebar }">
        <div class="search-sidebar-header">
          <h3>搜索历史</h3>
          <div class="header-actions">
            <button class="new-chat-btn" @click="newChat">新建对话</button>
            <button class="close-search-btn" @click="toggleSearchSidebar">×</button>
          </div>
        </div>
        <div class="search-content">
          <div v-for="(search, index) in searchHistory" :key="index" class="search-item">
            <div class="search-query">{{ search.query }}</div>
            <div class="search-time">{{ search.time }}</div>
            <button class="search-action-btn" @click="useSearch(search.query)">使用</button>
          </div>
          <div v-if="searchHistory.length === 0" class="no-search-history">
            暂无搜索历史
          </div>
        </div>
      </div>
      
      <div class="chat-messages" ref="messagesContainer">
        <div class="message ai-message">
          <div class="message-avatar">🤖</div>
          <div class="message-content">
            <p>您好！我是您的AI助手，有什么可以帮助您的吗？</p>
            <span class="message-time">刚刚</span>
          </div>
        </div>
        
        <div v-for="(message, index) in messages" :key="index" 
             :class="['message', message.type === 'user' ? 'user-message' : 'ai-message']">
          <div class="message-avatar">{{ message.type === 'user' ? '👤' : '🤖' }}</div>
          <div class="message-content">
            <p>{{ message.content }}</p>
            <div class="message-footer">
              <span class="message-time">{{ message.time }}</span>
              <div v-if="message.type === 'ai'" class="message-actions">
                <button class="action-btn regenerate-btn" @click="regenerateMessage(index)" title="重新生成">🔄</button>
                <button class="action-btn copy-btn" @click="copyMessage(message.content)" title="复制">📋</button>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <div class="chat-input-area">
        <div class="input-container">
          <textarea 
            v-model="inputMessage" 
            placeholder="请输入您的问题..." 
            @keydown.enter.exact.prevent="sendMessage"
            rows="3"
            ref="messageInput"
          ></textarea>
          <button class="send-btn" @click="sendMessage" :disabled="!inputMessage.trim()">
            <span class="send-icon">📤</span>
          </button>
        </div>
        <div class="quick-prompts">
          <button v-for="prompt in quickPrompts" :key="prompt" 
                  class="prompt-btn" @click="usePrompt(prompt)">
            {{ prompt }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'

// 响应式数据
const inputMessage = ref('')
const messages = ref([])
const messagesContainer = ref(null)
const messageInput = ref(null)
const showSearchSidebar = ref(false)

// 搜索历史数据
const searchHistory = ref([
  { query: 'Vue3组件开发最佳实践', time: '2024-01-15 10:30' },
  { query: 'JavaScript异步编程', time: '2024-01-14 16:20' },
  { query: 'CSS Grid布局教程', time: '2024-01-13 09:15' },
  { query: '前端性能优化技巧', time: '2024-01-12 14:45' }
])

// 快速提示语
const quickPrompts = ref([
  '帮我写一份项目计划',
  '解释一下Vue3的响应式原理',
  '推荐一些学习资源',
  '如何优化代码性能'
])

// 切换搜索侧边栏
const toggleSearchSidebar = () => {
  showSearchSidebar.value = !showSearchSidebar.value
}

// 使用搜索历史
const useSearch = (query) => {
  inputMessage.value = query
  toggleSearchSidebar()
  messageInput.value.focus()
}

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim()) return
  
  const userMessage = {
    type: 'user',
    content: inputMessage.value.trim(),
    time: '刚刚'
  }
  
  messages.value.push(userMessage)
  const userInput = inputMessage.value.trim()
  
  // 添加到搜索历史
  addToSearchHistory(userInput)
  
  inputMessage.value = ''
  
  // 滚动到底部
  await nextTick()
  scrollToBottom()
  
  // 模拟AI响应
  setTimeout(() => {
    const aiResponse = generateAIResponse(userInput)
    messages.value.push({
      type: 'ai',
      content: aiResponse,
      time: '刚刚'
    })
    
    // 再次滚动到底部
    nextTick(() => scrollToBottom())
  }, 1000)
}

// 添加到搜索历史
const addToSearchHistory = (query) => {
  const existingIndex = searchHistory.value.findIndex(item => item.query === query)
  if (existingIndex !== -1) {
    // 如果已存在，移到最前面
    const existingItem = searchHistory.value.splice(existingIndex, 1)[0]
    existingItem.time = new Date().toLocaleString('zh-CN', { 
      year: 'numeric', 
      month: '2-digit', 
      day: '2-digit', 
      hour: '2-digit', 
      minute: '2-digit' 
    })
    searchHistory.value.unshift(existingItem)
  } else {
    // 如果不存在，添加到最前面
    searchHistory.value.unshift({
      query: query,
      time: new Date().toLocaleString('zh-CN', { 
        year: 'numeric', 
        month: '2-digit', 
        day: '2-digit', 
        hour: '2-digit', 
        minute: '2-digit' 
      })
    })
    
    // 限制搜索历史数量
    if (searchHistory.value.length > 10) {
      searchHistory.value = searchHistory.value.slice(0, 10)
    }
  }
}

// 生成AI响应
const generateAIResponse = (userInput) => {
  const responses = [
    `感谢您的提问！关于"${userInput}"，我可以为您提供详细的解答。首先，让我们从基础概念开始...`,
    `这是一个很好的问题！${userInput}涉及到多个方面的知识。让我为您详细解释一下...`,
    `我理解您对${userInput}的疑问。基于我的知识库，我可以为您提供以下信息...`,
    `关于${userInput}，这是一个常见的问题。让我为您系统地分析一下...`
  ]
  return responses[Math.floor(Math.random() * responses.length)]
}

// 使用快速提示
const usePrompt = (prompt) => {
  inputMessage.value = prompt
  messageInput.value.focus()
}

// 新建对话
const newChat = () => {
  messages.value = []
}

// 清空历史
const clearHistory = () => {
  if (confirm('确定要清空所有对话历史吗？')) {
    messages.value = []
  }
}

// 打开新页面
const openNewPage = () => {
  window.open('/new-page', '_blank')
}

// 重新生成消息
const regenerateMessage = async (index) => {
  if (index > 0 && messages.value[index - 1].type === 'user') {
    const userMessage = messages.value[index - 1].content
    
    // 移除当前AI回复
    messages.value.splice(index, 1)
    
    // 滚动到底部
    await nextTick()
    scrollToBottom()
    
    // 生成新的AI回复
    setTimeout(() => {
      const aiResponse = generateAIResponse(userMessage)
      messages.value.push({
        type: 'ai',
        content: aiResponse,
        time: '刚刚'
      })
      
      // 再次滚动到底部
      nextTick(() => scrollToBottom())
    }, 1000)
  }
}

// 复制消息
const copyMessage = async (content) => {
  try {
    await navigator.clipboard.writeText(content)
    alert('内容已复制到剪贴板')
  } catch (err) {
    // 降级方案
    const textArea = document.createElement('textarea')
    textArea.value = content
    document.body.appendChild(textArea)
    textArea.select()
    document.execCommand('copy')
    document.body.removeChild(textArea)
    alert('内容已复制到剪贴板')
  }
}

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 自动调整输入框高度
const adjustTextareaHeight = () => {
  if (messageInput.value) {
    messageInput.value.style.height = 'auto'
    messageInput.value.style.height = messageInput.value.scrollHeight + 'px'
  }
}

// 生命周期
onMounted(() => {
  // 监听输入框变化
  if (messageInput.value) {
    messageInput.value.addEventListener('input', adjustTextareaHeight)
  }
  
  // 自动聚焦输入框
  messageInput.value.focus()
})
</script>

<style scoped>
.ai-chat-page {
  height: 100vh;
  padding: 20px;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  display: flex;
  flex-direction: column;
  position: relative;
}

/* AI对话区域 */
.chat-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  position: relative;
}

.chat-header {
  padding: 20px 30px;
  border-bottom: 1px solid #e0e0e0;
  background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
  color: #1e293b;
  border-radius: 12px;
  margin-bottom: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid #e2e8f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
}

.header-left {
  text-align: left;
}

.chat-header h1 {
  font-size: 1.5rem;
  margin-bottom: 5px;
}

.ai-status {
  opacity: 0.9;
  font-size: 0.9rem;
  color: #64748b;
  margin-top: 5px;
}

.search-toggle-btn {
  background: #f1f5f9;
  border: 1px solid #cbd5e1;
  color: #475569;
  padding: 10px 15px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.search-toggle-btn:hover {
  background: #e2e8f0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.search-icon {
  font-size: 18px;
}

.chat-messages {
  flex: 1;
  padding: 20px 30px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 20px;
  min-height: 0; /* 确保flex布局正确 */
  background: #ffffff;
  border-radius: 12px;
  margin-bottom: 20px;
  border: 1px solid #e2e8f0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.message {
  display: flex;
  margin-bottom: 20px;
  animation: fadeInUp 0.3s ease;
}

.ai-message {
  justify-content: flex-start;
}

.user-message {
  justify-content: flex-end;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.2rem;
  flex-shrink: 0;
}

.ai-message .message-avatar {
  background: #667eea;
  color: white;
  margin-right: 15px;
}

.user-message .message-avatar {
  background: #28a745;
  color: white;
  margin-left: 15px;
  order: 2;
}

.message-content {
  flex: 1;
  max-width: 70%;
}

.ai-message .message-content {
  order: 2;
}

.user-message .message-content {
  order: 1;
  text-align: right;
}

.message-content p {
  background: #f8f9fa;
  padding: 12px 16px;
  border-radius: 18px;
  margin-bottom: 5px;
  line-height: 1.5;
  word-wrap: break-word;
  display: inline-block;
}

.ai-message .message-content p {
  background: #f8fafc;
  border-bottom-left-radius: 5px;
  text-align: left;
  border-left: 3px solid #3498db;
}

.user-message .message-content p {
  background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
  color: white;
  border-bottom-right-radius: 5px;
  border-right: 3px solid #3498db;
}

.message-time {
  font-size: 0.8rem;
  color: #64748b;
  display: block;
}

.ai-message .message-time {
  text-align: left;
}

.user-message .message-time {
  text-align: right;
}

.message-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
}

.ai-message .message-footer {
  justify-content: space-between;
}

.user-message .message-footer {
  justify-content: flex-end;
}

.ai-message .message-actions {
  order: 2;
  margin-left: auto;
}

.user-message .message-actions {
  order: 2;
  margin-left: auto;
}

.message-actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  width: 28px;
  height: 28px;
  border: none;
  border-radius: 6px;
  background: rgba(255, 255, 255, 0.1);
  color: #666;
  cursor: pointer;
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.action-btn:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: scale(1.1);
}

.regenerate-btn:hover {
  background: rgba(74, 144, 226, 0.2);
  color: #4a90e2;
}

.copy-btn:hover {
  background: rgba(52, 199, 89, 0.2);
  color: #34c759;
}

.chat-input-area {
  padding: 20px 30px;
  border-top: 1px solid #e9ecef;
  background: #ffffff;
  border-radius: 12px;
  border: 1px solid #e2e8f0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.input-container {
  display: flex;
  align-items: flex-end;
  gap: 10px;
  margin-bottom: 15px;
}

.input-container textarea {
  flex: 1;
  border: 1px solid #cbd5e1;
  border-radius: 8px;
  padding: 15px;
  font-size: 1rem;
  resize: none;
  outline: none;
  transition: all 0.3s ease;
  min-height: 80px;
  max-height: 150px;
  line-height: 1.5;
  background: #ffffff;
  color: #1e293b;
}

.input-container textarea:focus {
  border-color: #3b82f6;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2);
}

.send-btn {
  width: 44px;
  height: 44px;
  border: none;
  border-radius: 50%;
  background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
  color: white;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.3);
}

.send-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.4);
}

.send-btn:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
  box-shadow: none;
}

.quick-prompts {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.prompt-btn {
  background: #f1f5f9;
  border: 1px solid #cbd5e1;
  color: #475569;
  padding: 8px 16px;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 0.9rem;
}

.prompt-btn:hover {
  background: #e2e8f0;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 动画 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 搜索侧边栏样式 */
.search-sidebar {
  position: fixed;
  top: 0;
  right: 0;
  width: 300px;
  height: 100vh;
  background: white;
  box-shadow: -2px 0 10px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  transform: translateX(100%);
  transition: transform 0.3s ease;
  display: flex;
  flex-direction: column;
}

.search-sidebar.active {
  transform: translateX(0);
}

.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #e9ecef;
}

.new-chat-btn {
  padding: 8px 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.new-chat-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.close-search-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #6c757d;
  transition: color 0.3s ease;
}

.close-search-btn:hover {
  color: #495057;
}

.search-sidebar-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-sidebar-header h3 {
  margin: 0;
  font-size: 1.3em;
}

.close-search-btn {
  background: none;
  border: none;
  color: white;
  font-size: 24px;
  cursor: pointer;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background 0.3s ease;
}

.close-search-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

.search-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.search-item {
  background: #f8f9fa;
  border-radius: 10px;
  padding: 15px;
  margin-bottom: 10px;
  border: 1px solid #e9ecef;
  transition: all 0.3s ease;
}

.search-item:hover {
  background: #e9ecef;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.search-query {
  font-weight: 600;
  color: #333;
  margin-bottom: 5px;
  font-size: 14px;
}

.search-time {
  font-size: 12px;
  color: #6c757d;
  margin-bottom: 10px;
}

.search-action-btn {
  background: #667eea;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 15px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.search-action-btn:hover {
  background: #5a6fd8;
  transform: translateY(-1px);
}

.no-search-history {
  text-align: center;
  color: #6c757d;
  font-style: italic;
  padding: 40px 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .ai-chat-page {
    flex-direction: column;
    height: auto;
  }
  
  .user-sidebar {
    width: 100%;
    border-right: none;
    border-bottom: 1px solid #e9ecef;
    padding: 15px;
  }
  
  .user-profile {
    justify-content: center;
    text-align: center;
  }
  
  .user-avatar {
    width: 50px;
    height: 50px;
  }
  
  .user-name {
    font-size: 14px;
  }
  
  .user-status {
    font-size: 11px;
  }
  
  .sidebar-stats .stat-item {
    padding: 8px 0;
  }
  
  .quick-actions {
    flex-direction: column;
    gap: 8px;
  }
  
  .action-btn {
    width: 100%;
    padding: 8px;
  }
  
  .chat-container {
    margin: 10px 0;
    border-radius: 0;
  }
  
  .chat-header {
    padding: 20px;
  }
  
  .chat-header h1 {
    font-size: 1.8em;
  }
  
  .ai-status {
    font-size: 1em;
  }
  
  .message-content {
    max-width: 85%;
  }
  
  .message-avatar {
    width: 35px;
    height: 35px;
    font-size: 16px;
  }
  
  .message-content p {
    padding: 12px 15px;
    font-size: 14px;
  }
  
  .message-time {
    font-size: 10px;
  }
  
  .chat-input-area {
    padding: 15px;
  }
  
  .input-container textarea {
    padding: 12px 15px;
    font-size: 14px;
  }
  
  .send-btn {
    width: 45px;
    height: 45px;
  }
  
  .quick-prompts {
    justify-content: center;
    padding: 10px 15px;
  }
  
  .prompt-btn {
    padding: 6px 12px;
    font-size: 12px;
  }
  
  .search-sidebar {
    width: 280px;
  }
  
  .search-toggle-btn {
    padding: 8px 15px;
    font-size: 12px;
  }
  
  .search-sidebar-header {
    padding: 15px;
  }
  
  .search-sidebar-header h3 {
    font-size: 1.1em;
  }
}
</style>